using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;
using System.Collections.Generic;
using Ent.Web.Helper;
/// <summary>
/// Summary description for Helper
/// </summary>
public class ResourceHelper
{
    private static Dictionary<string, string> _langCode = null;
    ResourceHelper()
    {
        if (_langCode == null)
        {
            _langCode = new Dictionary<string, string>();
            string dataFile = HttpRuntime.AppDomainAppPath + "/" + (ConfigurationManager.AppSettings.Get("Language"));
            XMLHelper xml = new XMLHelper(dataFile);
            _langCode = xml.GetNameValuePair("//Globalisation", "Language", "name", "value");
        }
    }
    public static Dictionary<string, string> GetLanguages()
    {
        new ResourceHelper();
        return _langCode;
    }
    public static void Init()
    {
        new ResourceHelper();
    }
    public static string Get(string name)
    {
        ResourceManager rm = GetResourceManager(GetLanguage());
        return rm.GetString(name);
    }
    public static string Get(string name, Dictionary<string, string> replacements)
    {
        ResourceManager rm = GetResourceManager(GetLanguage());
        string orgText = rm.GetString(name);
        foreach (string s in replacements.Keys)
        {
            orgText = orgText.Replace(s, replacements[s]);
        }
        return orgText;
    }
    private static ResourceManager GetResourceManager(string lang)
    {
        Init();
        if (!_langCode.ContainsValue(lang))
            lang = "en_US";
        if (HttpContext.Current.Application["LANG_" + lang] == null)
        {
            try
            {
                System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(Resources.en_US));
                Type t = asm.GetType("Resources." + lang, true, true);
                ResourceManager rm = new ResourceManager(t);
                HttpContext.Current.Application["LANG_" + lang] = rm;
                return rm;
            }
            catch (Exception exc)
            {
                Common.Log.Error(exc);
                ResourceManager rm = new ResourceManager(typeof(Resources.en_US));
                HttpContext.Current.Application["LANG_" + lang] = rm;
                return rm;
            }
        }
        else
            return (ResourceManager)HttpContext.Current.Application["LANG_" + lang];
    }
    private static string GetLanguage()
    {
        if (HttpContext.Current.Session["LANG"] != null)
            return HttpContext.Current.Session["LANG"].ToString();
        else
            return "";
    }
}
